<script setup>
import { onMounted, ref, onUnmounted } from 'vue'
import * as echarts from 'echarts'
import { useInference } from '@/composables/useInference'
import emitter from '@/utils/eventBus'

const { getTaskProgress } = useInference()

// 初始化为空数组
const accuracyHistory = ref(new Array(10).fill(0))
const lossHistory = ref(new Array(10).fill(0))

let accuracyChart = null
let lossChart = null

const initCharts = () => {
  accuracyChart = echarts.init(document.getElementById('accuracyChart'))
  lossChart = echarts.init(document.getElementById('lossChart'))

  const accuracyOption = {
    title: { 
      text: '准确率趋势',
      textStyle: {
        color: '#7ecbcf',
        fontSize: 12,
        fontWeight: 'normal'
      },
      left: 'center'
    },
    tooltip: {
      trigger: 'axis',
      axisPointer: {
        type: 'line',
        lineStyle: {
          color: '#3eacb4',
          width: 1,
          type: 'dashed'
        }
      }
    },
    grid: {
      top: '25%',
      left: '15%',
      right: '15%',
      bottom: '12%'
    },
    xAxis: { 
      type: 'category',
      boundaryGap: false,
      data: Array.from({length: 10}, (_, i) => `E${i + 1}`), // 固定10个epoch
      axisLabel: { 
        color: '#a8c1c3',
        fontSize: 10
      },
      axisLine: {
        show: false
      },
      axisTick: {
        show: false
      }
    },
    yAxis: { 
      type: 'value',
      min: 50,
      max: 100,
      axisLabel: { 
        color: '#a8c1c3',
        fontSize: 10,
        formatter: '{value}'
      },
      splitLine: {
        lineStyle: {
          color: 'rgba(62, 172, 180, 0.1)'
        }
      },
      axisLine: {
        show: false
      },
      axisTick: {
        show: false
      }
    },
    series: [{
      name: '准确率',
      type: 'line',
      smooth: true,
      symbol: 'circle',
      symbolSize: 6,
      data: accuracyHistory.value,
      lineStyle: {
        width: 3,
        color: new echarts.graphic.LinearGradient(0, 0, 1, 0, [
          { offset: 0, color: '#3eacb4' },
          { offset: 1, color: '#09c4ca' }
        ])
      },
      itemStyle: {
        color: '#3eacb4',
        borderWidth: 2,
        borderColor: '#fff'
      },
      areaStyle: {
        color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [
          { offset: 0, color: 'rgba(62, 172, 180, 0.3)' },
          { offset: 1, color: 'rgba(62, 172, 180, 0.05)' }
        ])
      }
    }]
  }

  const lossOption = {
    title: { 
      text: '损失值趋势',
      textStyle: {
        color: '#7ecbcf',
        fontSize: 12,
        fontWeight: 'normal'
      },
      left: 'center'
    },
    tooltip: {
      trigger: 'axis',
      axisPointer: {
        type: 'line',
        lineStyle: {
          color: '#f29701',
          width: 1,
          type: 'dashed'
        }
      }
    },
    grid: {
      top: '25%',
      left: '15%',
      right: '15%',
      bottom: '12%'
    },
    xAxis: { 
      type: 'category',
      boundaryGap: false,
      data: Array.from({length: 10}, (_, i) => `E${i + 1}`), // 固定10个epoch
      axisLabel: { 
        color: '#a8c1c3',
        fontSize: 10
      },
      axisLine: {
        show: false
      },
      axisTick: {
        show: false
      }
    },
    yAxis: { 
      type: 'value',
      min: 0,
      max: 0.6,
      axisLabel: { 
        color: '#a8c1c3',
        fontSize: 10
      },
      splitLine: {
        lineStyle: {
          color: 'rgba(242, 151, 1, 0.1)'
        }
      },
      axisLine: {
        show: false
      },
      axisTick: {
        show: false
      }
    },
    series: [{
      name: '损失值',
      type: 'line',
      smooth: true,
      symbol: 'circle',
      symbolSize: 6,
      data: lossHistory.value,
      lineStyle: {
        width: 3,
        color: new echarts.graphic.LinearGradient(0, 0, 1, 0, [
          { offset: 0, color: '#f29701' },
          { offset: 1, color: '#e07b00' }
        ])
      },
      itemStyle: {
        color: '#f29701',
        borderWidth: 2,
        borderColor: '#fff'
      },
      areaStyle: {
        color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [
          { offset: 0, color: 'rgba(242, 151, 1, 0.3)' },
          { offset: 1, color: 'rgba(242, 151, 1, 0.05)' }
        ])
      }
    }]
  }

  accuracyChart.setOption(accuracyOption)
  lossChart.setOption(lossOption)
}

// 修改 updateData 函数
const updateData = (accList, lossList) => {
  // 找到最后一个非零值的索引
  const lastAccIndex = accList.findLastIndex(v => v !== 0)
  const lastLossIndex = lossList.findLastIndex(v => v !== 0)
  
  // 确保至少保留一个值，即使是0
  const finalAccIndex = lastAccIndex >= 0 ? lastAccIndex + 1 : accList.length
  const finalLossIndex = lastLossIndex >= 0 ? lastLossIndex + 1 : lossList.length

  // 更新数据
  accuracyHistory.value = accList.slice(0, finalAccIndex)
  lossHistory.value = lossList.slice(0, finalLossIndex)

  // 更新图表
  if (accuracyChart && lossChart) {
    accuracyChart.setOption({
      series: [{
        data: accuracyHistory.value
      }]
    })
    
    lossChart.setOption({
      series: [{
        data: lossHistory.value
      }]
    })
  }

  // 发送最新的非零性能数据到事件总线
  const latestAcc = accuracyHistory.value[lastAccIndex]
  const latestLoss = lossHistory.value[lastLossIndex]
  if (latestAcc !== undefined && latestLoss !== undefined && latestAcc !== 0) {
    emitter.emit('performance-update', {
      accuracy: latestAcc,
      loss: latestLoss
    })
  }
}

// 修改获取实时数据的函数
const getCurrentTaskProgress = async () => {
  try {
    const res = await getTaskProgress('latest')
    if (res && res.acc && res.loss) {
      // 只调用 updateData，让它来处理事件发送
      updateData(res.acc, res.loss)
    }
  } catch (error) {
    console.error('获取任务进度失败:', error)
  }
}

let intervalId = null

onMounted(() => {
  initCharts()
  
  // 立即获取一次数据
  getCurrentTaskProgress()
  
  // 启动定时器获取实时数据
  intervalId = setInterval(() => {
    getCurrentTaskProgress()
  }, 5000) // 每5秒更新一次
})

onUnmounted(() => {
  if (intervalId) {
    clearInterval(intervalId)
    intervalId = null
  }
  if (accuracyChart) accuracyChart.dispose()
  if (lossChart) lossChart.dispose()
})
</script>

<template>
  <div class="model-performance">
    <h3>模型性能指标</h3>
    <div id="accuracyChart" class="chart"></div>
    <div id="lossChart" class="chart"></div>
  </div>
</template>

<style lang="scss" scoped>
.model-performance {
  height: 100%;
  color: rgba(255, 255, 255, 0.8);
  
  h3 {
    margin-bottom: 15px;
    font-size: 0.9rem;
    font-weight: 500;
    text-align: center;
    color: #7ecbcf;
    letter-spacing: var(--letter-spacing-base);
  }
  
  .chart {
    width: 100%;
    height: 40%;
    margin-bottom: 10px;
    opacity: 0.8;
  }
}
</style> 